﻿using AutoMapper;
using Azure;
using FakeXiecheng.API.Dto;
using FakeXiecheng.API.Dtos;
using FakeXiecheng.API.Helper;
using FakeXiecheng.API.Models;
using FakeXiecheng.API.ResourceParameters;
using FakeXiecheng.API.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace FakeXiecheng.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TouristRoutesController : ControllerBase
    {
        private ITouristRouteRepository _touristRouteRepository;
        private readonly IMapper _mapper;

        public TouristRoutesController(ITouristRouteRepository touristRouteRepository, IMapper mapper)
        {
            _touristRouteRepository = touristRouteRepository;
            _mapper = mapper;
        }

        [HttpGet]
        [HttpHead]                  // rating的值为：lessThan3, largerThan2, equalTo5 找规律正则表达式
        public async Task<IActionResult> GetTouristRoutes([FromQuery] TouristRouteParamaters param)
        {

            var TouristRoutesFromRepo = await _touristRouteRepository.GetTouristRoutesAsync(param.Keyword, param.RatingOperator, param.RatingValue);

            if (TouristRoutesFromRepo == null)
            {
                return NotFound("没有找到旅游路线");
            }
            var TourstRouteDTO = _mapper.Map<IEnumerable<TouristRouteDTO>>(TouristRoutesFromRepo);

            return Ok(TourstRouteDTO);
        }


        // GET: api/TouristRoutes/5
        [HttpHead("{TouristRouteId}")]
        [HttpGet("{TouristRouteId}", Name = "GetTouristRoutesById")]
        public async Task<IActionResult> GetTouristRoutesById(Guid touristRouteId)
        {
            var TouristRoutesFromRepo = await _touristRouteRepository.GetTouristRouteAsync(touristRouteId);
            if (TouristRoutesFromRepo == null)
            {
                return NotFound($"没有找到ID为：{touristRouteId}的旅游路线");
            }

            //手动映射字段
            /* var TouristRouteDTO = new TouristRouteDTO()
             {
                 Id = TouristRoutesFromRepo.Id,
                 Title = TouristRoutesFromRepo.Title,
                 Description = TouristRoutesFromRepo.Description,
                 Price = TouristRoutesFromRepo.OriginalPrice * (decimal)(TouristRoutesFromRepo.DiscountPresent ?? 1),//discount为空的时候，默认为1 不为空时候，取本身值
                 CreateTime = TouristRoutesFromRepo.CreateTime,
                 UpdateTime = TouristRoutesFromRepo.UpdateTime,
                 Features = TouristRoutesFromRepo.Features,
                 Fees = TouristRoutesFromRepo.Fees,
                 Notes = TouristRoutesFromRepo.Notes,
                 Rating = TouristRoutesFromRepo.Rating,
                 TravelDays = TouristRoutesFromRepo.TravelDays.ToString(),
                 TripType = TouristRoutesFromRepo.TripType.ToString(),
                 DepartureCity = TouristRoutesFromRepo.DepartureCity.ToString()
             };*/


            //使用mapper自动映射字段
            var TouristRouteDTO = _mapper.Map<TouristRouteDTO>(TouristRoutesFromRepo);


            return Ok(TouristRouteDTO);
        }


        /// <summary>
        /// 新增路线数据方法
        /// </summary>
        /// <param name="createDTO"></param>
        /// <returns></returns>
        [Authorize(Roles ="Admin")]
        [HttpPost]
        public async Task<IActionResult> AddTouristRoutes([FromBody] TouristRouteForCreateDTO createDTO)
        {
            var touristRoute = _mapper.Map<TouristRoute>(createDTO);
            _touristRouteRepository.AddTouristRoute(touristRoute);
            _touristRouteRepository.SaveAsync();//向数据库插入数据
            var resultDTO = _mapper.Map<TouristRouteDTO>(touristRoute);

            return CreatedAtRoute("GetTouristRoutesById",
                new { touristRouteId = touristRoute.Id },
                resultDTO);
        }

        /// <summary>
        /// PUT全量更新旅游路线  
        /// </summary>
        /// <param name="touristRouteId"></param>
        /// <param name="touristRouteDTO"></param>
        /// <returns></returns>
        [HttpPut("{touristRouteId}")]
        public async Task<IActionResult> UpdateToursitRoute([FromRoute] Guid touristRouteId, [FromBody] TouristRouteForUpdateDTO touristRouteDTO)
        {
            if (!await _touristRouteRepository.TouristRoutesExistAsync(touristRouteId))
            {
                return NotFound("路线不存在");
            }

            var toursitRoute =await _touristRouteRepository.GetTouristRouteAsync(touristRouteId);
            _mapper.Map(touristRouteDTO, toursitRoute);
            await _touristRouteRepository.SaveAsync(); //更新数据

            return NoContent();
        }


        /// <summary>
        /// JSONPatch增量更新
        /// </summary>
        /// <param name="touristRouteId"></param>
        /// <param name="patchDocumentParam"></param>
        /// <returns></returns>
        [HttpPatch("{touristRouteId}")]
        public async Task<IActionResult> PatchUpdateTouristRoute([FromRoute] Guid touristRouteId, [FromBody] JsonPatchDocument<TouristRouteForUpdateDTO> patchDocumentParam)
        {
            if (!await _touristRouteRepository.TouristRoutesExistAsync(touristRouteId))
            {
                return NotFound("旅游路线不存在");
            }

            var toursitRoute =await _touristRouteRepository.GetTouristRouteAsync(touristRouteId);
            var toursitRouteUpdateParam = _mapper.Map<TouristRouteForUpdateDTO>(toursitRoute);
            patchDocumentParam.ApplyTo(toursitRouteUpdateParam, ModelState);//将前端传递过来的操作，应用到toursitRouteUpdateParam上

            if (!TryValidateModel(toursitRouteUpdateParam))
            {
                return ValidationProblem(ModelState);
            }

            _mapper.Map(toursitRouteUpdateParam, toursitRoute);
            await _touristRouteRepository.SaveAsync();


            return NoContent();
        }


        /// <summary>
        /// 删除单一资源
        /// </summary>
        /// <param name="touristRouteId"></param>
        /// <returns></returns>
        [HttpDelete("{touristRouteId}")]
        public async Task<IActionResult> DeleteTouristRouteById(Guid touristRouteId)
        {
            if (!await _touristRouteRepository.TouristRoutesExistAsync(touristRouteId))
            {
                return NotFound("路线不存在，删除失败！");
            }

            var touristRoute =await _touristRouteRepository.GetTouristRouteAsync(touristRouteId);
            _touristRouteRepository.DeleteTouristRoute(touristRoute);
            await _touristRouteRepository.SaveAsync();


            return NoContent();
        }


        /// <summary>
        /// 批量删除指定资源
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete("({ids})")]
        public async Task<IActionResult> BatchDeleteTouristRoutes([ModelBinder(BinderType = typeof(ArrayModelBinder))][FromRoute] IEnumerable<Guid> ids)
        {
            if (!ids.Any())
            {
                return NotFound("参数为空！");
            }

            var touristRoutes =await _touristRouteRepository.GetBatchTouristRouteAsync(ids);
            _touristRouteRepository.BatchDeleteTouristRoute(touristRoutes);
            await _touristRouteRepository.SaveAsync();

            return NoContent();
        }

    }
}